<script setup lang="ts">
  import { ref, watch } from 'vue'
  import {
    getUserRelationCodeGoodsList,
    getUserRelationInfo,
    getUserRelationOrderList,
  } from '@/api/users'
  import { ElMessage, TabsPaneContext } from 'element-plus'
  import { tableHeaderCellStyle } from '@/utils/tools'
  import Pagination from '@/components/Pagination/index.vue'
  import {
    UserRelationGood,
    UserRelationInfoDetail,
    UserRelationOrder,
  } from '@/views/order/list/odetail/components/CustomerAssociatedFiles/types'
  import HLink from '@/components/common/link/HLink.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import { Refresh } from '@element-plus/icons-vue'

  const props = defineProps({
    userName: {
      type: String,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
  })

  // 工单id
  const workId = ref('')

  // 客户关联
  const activeUserName = ref('userRelationGoods')

  // 抽屉显示状态
  const drawerVisible = ref(false)

  /**
   * 显示客户关联信息抽屉
   */
  const onShow = async () => {
    drawerVisible.value = true
    await getUserRelationInfoData()
  }

  // 客户工单商品信息
  const userRelationInfoDetail = ref<UserRelationInfoDetail | null>(null)

  // 根据工单ID获取客户关联信息加载
  const getUserRelationInfoDataLoading = ref(false)

  // 根据工单ID获取客户关联信息方法
  const getUserRelationInfoData = async () => {
    if (workId.value) {
      getUserRelationInfoDataLoading.value = true
      const res = await getUserRelationInfo(workId.value)
      if (res.data.success) {
        userRelationInfoDetail.value = res.data.data.row
        await getUserRelationGoods()
      } else {
        if(res.data.isError) ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
      }
      getUserRelationInfoDataLoading.value = false
    }
  }

  // 关联商品分页组件实例
  const paginationGoods = ref<InstanceType<typeof Pagination> | null>(null)

  // 客户关联商品列表
  const UserRelationCodeGoodsList = ref<{ rows: Array<UserRelationGood>; total: number }>({
    rows: [],
    total: 0,
  })

  // 获取客户关联商品列表加载
  const getUserRelationGoodsLoading = ref(false)

  /**
   * 获取客户关联商品列表
   */
  const getUserRelationGoods = async () => {
    if (!userRelationInfoDetail.value) {
      return false
    }
    let data = {
      limit: paginationGoods.value.size || 50,
      page: paginationGoods.value.current || 1,
    }
    getUserRelationGoodsLoading.value = true
    const res = await getUserRelationCodeGoodsList(data, userRelationInfoDetail.value.userId)
    if (res.data.success) {
      UserRelationCodeGoodsList.value = res.data.data
    } else {
      if(res.data.isError) ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 3000,
      })
    }
    getUserRelationGoodsLoading.value = false
  }

  // 客户关联工单分页组件实例
  const paginationOrder = ref<InstanceType<typeof Pagination> | null>(null)

  // 获取客户关联工单列表
  const UserRelationOrderList = ref<{ rows: Array<UserRelationOrder>; total: number }>({
    rows: [],
    total: 0,
  })

  // 获取客户关联工单加载
  const getUserRelationOrdersLoading = ref(false)

  /**
   * 获取客户关联工单
   */
  const getUserRelationOrders = async () => {
    if (!userRelationInfoDetail.value) {
      return false
    }
    const data = {
      limit: paginationOrder.value.size || 50,
      page: paginationOrder.value.current || 1,
    }
    getUserRelationOrdersLoading.value = true
    const res = await getUserRelationOrderList(data, userRelationInfoDetail.value.userId)
    if (res.data.success) {
      UserRelationOrderList.value = res.data.data
    } else {
      if(res.data.isError) ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 3000,
      })
    }
    getUserRelationOrdersLoading.value = false
  }

  /**
   * 标签点击事件
   * @param {TabsPaneContext} pane 标签点击事件参数
   */
  const handleTableClick = (pane: TabsPaneContext) => {
    if (pane.props.name === 'userRelationOrders') {
      getUserRelationOrders()
    }

    if (pane.props.name === 'userRelationGoods') {
      getUserRelationGoods()
    }
  }

  watch(
    () => props.orderId,
    (value) => {
      workId.value = value
    },
    { immediate: true },
  )
</script>

<template>
  <div style="display: flex; align-items: center">
    <HLink @click="onShow">{{ props.userName }}</HLink>

    <el-drawer v-model="drawerVisible" show-close size="60%">
      <template #header>
        <div class="title">
          <span class="text">客户关联档案表</span>
          <i class="iconfont icon-shuaxin1" @click="getUserRelationInfoData"></i>
        </div>
      </template>

      <div
        element-loading-text="加载中..."
        v-loading="
          getUserRelationOrdersLoading ||
          getUserRelationGoodsLoading ||
          getUserRelationInfoDataLoading
        "
      >
        <el-form
          v-if="userRelationInfoDetail"
          :model="userRelationInfoDetail"
          class="basic_information"
          label-position="top"
        >
          <el-form-item>
            <template #label>
              <span class="label">客户名称：</span>
            </template>
            <span class="ml" @click="onShow">
              {{ userRelationInfoDetail.userName }}
            </span>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="label">联系人电话：</span>
            </template>
            <span class="ml">{{ userRelationInfoDetail.userPhone }}</span>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="label">关联工单量：</span>
            </template>
            <span class="ml">{{ userRelationInfoDetail.orderQty }}</span>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="label">关联商品量：</span>
            </template>
            <span class="ml">{{ userRelationInfoDetail.goodsQty }}</span>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="label">创建时间：</span>
            </template>
            <span class="ml">{{ userRelationInfoDetail.userCreateTime }}</span>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="label">客户编码：</span>
            </template>
            <span class="ml">{{ userRelationInfoDetail.userCode }}</span>
          </el-form-item>
        </el-form>
        <el-tabs v-model="activeUserName" @tab-click="handleTableClick">
          <!-- 关联商品 -->
          <el-tab-pane
            :label="`关联商品（${userRelationInfoDetail?.goodsQty}）`"
            name="userRelationGoods"
          >
            <el-table
              :border="true"
              :data="UserRelationCodeGoodsList.rows"
              resizable
              stripe
              height="75vh"
              style="width: 100%"
              :header-cell-style="tableHeaderCellStyle"
              v-loading="getUserRelationGoodsLoading"
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column label="序号" width="50">
                <template #default="scope">
                  <div>
                    {{ scope.$index + 1 }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="商品信息">
                <template #default="scope">
                  {{ scope.row.goodsBrand }}&nbsp;{{ scope.row.goodsName }}&nbsp;{{
                    scope.row.goodsModel
                  }}&nbsp;{{ scope.row.goodsSpecName }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="70">
                <template #default="scope">
                  <HStatus v-if="scope.row.status !== 2" type="info">禁用</HStatus>
                  <HStatus v-else>启用</HStatus>
                </template>
              </el-table-column>
              <el-table-column prop="code" show-overflow-tooltip label="商品编号" width="180" />
              <el-table-column
                prop="registerTime"
                show-overflow-tooltip
                label="登记时间"
                width="150"
              />
            </el-table>
            <div style="display: flex; justify-content: flex-end; margin-top: 12px">
              <Pagination
                ref="paginationGoods"
                :list_total="Number(UserRelationCodeGoodsList?.total || 0)"
                @size-change="getUserRelationGoods"
                @current-change="getUserRelationGoods"
              />
            </div>
          </el-tab-pane>

          <!-- 关联工单 -->
          <el-tab-pane
            :label="`关联工单（${userRelationInfoDetail?.orderQty}）`"
            name="userRelationOrders"
          >
            <el-table
              :border="true"
              :data="UserRelationOrderList.rows"
              resizable
              stripe
              height="75vh"
              style="width: 100%"
              :header-cell-style="tableHeaderCellStyle"
              v-loading="getUserRelationOrdersLoading"
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <el-table-column label="序号" width="50">
                <template #default="scope">
                  <span> {{ scope.$index + 1 }} </span>
                </template>
              </el-table-column>
              <el-table-column prop="workNo" show-overflow-tooltip label="工单编码" width="180" />
              <el-table-column show-overflow-tooltip prop="status" label="状态" width="120">
                <template #default="scope">
                  <div style="display: flex; justify-content: center">
                    <HStatus type="warning" v-if="scope.row.status === 1">待派单</HStatus>
                    <HStatus type="warning" v-if="scope.row.status === 2">待服务商确认</HStatus>
                    <HStatus type="warning" v-if="scope.row.status === 3">处理中</HStatus>
                    <HStatus type="success" v-if="scope.row.status === 4">已完成</HStatus>
                    <HStatus type="info" v-if="scope.row.status === 5">已取消</HStatus>
                  </div>
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="商品信息">
                <template #default="scope">
                  {{ scope.row.goodsBrand }}&nbsp;{{ scope.row.goodsName }}&nbsp;{{
                    scope.row.goodsModel
                  }}&nbsp;{{ scope.row.goodsSpecName }}
                </template>
              </el-table-column>
              <el-table-column
                prop="createTime"
                show-overflow-tooltip
                label="创建时间"
                width="150"
              />
              <el-table-column prop="endTime" show-overflow-tooltip label="完成时间" width="150" />
            </el-table>
            <div style="display: flex; justify-content: flex-end; margin-top: 12px">
              <Pagination
                ref="paginationOrder"
                :list_total="Number(UserRelationOrderList?.total || 0)"
                @size-change="getUserRelationOrders"
                @current-change="getUserRelationOrders"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
  @import './CustomerConnect.scss';
</style>
